<template>
  <!-- 自动补全 -->
  <el-autocomplete
    style="width: 100%"
    v-model="vValue"
    placeholder="Please Input"
    :highlight-first-item="false"
    :debounce="500"
    :clearable="false"
    :teleported="true"
    :fetch-suggestions="querySearch"
    :loading="loading"
    :value-key="noValueKey || valueKey"
    v-bind="attrs"
    @select="itemEvent($event)"
  />
</template>

<script setup>
import { vModelValue } from '@/utils/hooks.js';
import { apiMethods } from '@/utils/http.js';

const attrs = useAttrs();

const emits = defineEmits(['update:modelValue', 'itemEvent']);
const { newValue: key } = vModelValue(props, emits);
let vValue = ref(key);

const loading = ref(false);

const props = defineProps({
  modelValue: {
    type: [String, Array],
  },
  prop: {
    type: String,
    default: '',
  },
  axiosMethod: {
    type: String,
    default: 'post',
  },
  valueKey: {
    type: String,
    default: '',
  },
  noValueKey: {
    // 后端返回的数据是字符串的数组，要拼成对象的数组对应的 key
    type: String,
    default: '',
  },
});

async function querySearch(queryString, cb) {
  let arr = [];
  if (queryString && queryString !== 'null') {
    loading.value = true;
    let res = await apiMethods[props.axiosMethod](attrs.requestUrl, {
      searchKey: queryString,
      ...attrs.params,
    });
    if (props.noValueKey && res?.data?.data?.length) {
      res.data.data.forEach(item => {
        let obj = {};
        obj[props.noValueKey] = item;
        arr.push(obj);
      });
    } else {
      arr = res.data.data || [];
    }
    cb(arr);
    loading.value = false;
  } else {
    cb(arr);
    loading.value = false;
  }
}

function itemEvent($event) {
  emits('itemEvent', {
    eventName: 'change',
    value: $event,
    prop: props.prop,
  });
}
</script>

<style></style>
